package com.hula.onion.book.server.spider.platforms.jinxinwang;

import com.alibaba.fastjson.JSONObject;
import com.hula.onion.book.server.common.CommonResponse;
import com.hula.onion.book.server.common.SpiderCommon;
import com.hula.onion.book.server.config.ResponseStatusEnum;
import com.hula.onion.book.server.model.AccountInfo;
import com.hula.onion.book.server.utils.HttpUtils;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.client.BasicCookieStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * Description:金信网
 * Create Date:2018/1/17 19:33
 *
 * @author shan
 * @version 1.0
 */
@Component("jinXinWangSpider")
public class JinXinWangSpider extends SpiderCommon {

    /**
     * 登录URL
     */
    private static final String LOGIN_URL = "http://www.jinxin99.cn/ssl/login.do";

    /**
     * 获取账户信息URL
     */
    private static final String GET_ACCOUNT_INFO_URL = "http://www.jinxin99.cn/cunguan/account/getMyTotalMoney.do";

    @Autowired
    private JinXinWangSpiderHelper jinXinWangSpiderHelper;

    /**
     * 执行爬取操作
     */
    @Override
    public CommonResponse execute() {

        CommonResponse commonResponse = new CommonResponse(ResponseStatusEnum.FAIL);
        //1.1 组装模拟登陆参数
        HttpClientContext httpContext = HttpClientContext.create();
        BasicCookieStore cookieStore = new BasicCookieStore();
        httpContext.setCookieStore(cookieStore);

        try {
            Map<String, Object> params = jinXinWangSpiderHelper.installRequestParams(loginForm);

            //2. 模拟登陆
            String responseStr = HttpUtils.post(LOGIN_URL, params, httpContext);
            logger.info("[JinXinWangSpider] Http response result:{}", responseStr);

            //登陆成功
            if (responseStr.contains("success")) {

                //2.1 爬取用户详细信息
                String result = HttpUtils.post(GET_ACCOUNT_INFO_URL, null, httpContext);

                logger.info("[JinXinWangSpider] Http response account result:{}", result);

                //2.2 解析html
                AccountInfo accountInfo = jinXinWangSpiderHelper.parseAccountBalance(result);

                commonResponse = new CommonResponse(ResponseStatusEnum.SUCCESS);
                commonResponse.setData(accountInfo);

            } else {
                commonResponse = new CommonResponse(ResponseStatusEnum.ACCOUNT_ERROR);
            }

        } catch (Exception e) {
            logger.error("[xiaoYouCaiSpider] Install request params error!");
        }

        return commonResponse;
    }


    @Override
    public String getLoginPageURL() {
        return LOGIN_URL;
    }

}

